<template>
  <view>
    <Item v-for="item in state.list" :key="item.filmId" />

    <view v-if="state.hasMore" class="loading">加载中...</view>
    <view v-else class="nomore">别拉了，没有了</view>
  </view>
</template>

<script lang="ts" setup>
import Item from "./components/item.vue";
import { reactive, onMounted } from "vue";
import { onReachBottom, onPullDownRefresh } from "@dcloudio/uni-app";
import { getFilmList } from "@/api/film";

// 请求参数
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  cityId: 440300,
  type: 1,
});

// 接口返回值数据的存储
const state = reactive({
  list: [] as API.IFilm[],
  total: 0 as number,
  hasMore: true, // 是否还有下一页
});

// 请求数据的方法
const load = async (callback?: Function) => {
  // 调用接口
  const data = await getFilmList(query);
  // 写入 state
  state.list = [...state.list, ...data.films];
  state.total = data.total;
  // 计算 hasMore
  state.hasMore = state.list.length < data.total;
  // 执行 callback 回调
  callback && callback();
};

/**
 * 触底事件
 * 		可以配置 onReachBottomDistance 做距离底部距离控制，默认是 50px
 */
onReachBottom(() => {
  // 判断是否加载更多
  if (!state.hasMore) {
    return;
  }
  query.pageNum++;
  load();
});

/**
 * 下拉事件
 * 		1. 页面需要开启下拉刷新	enablePullDownRefresh
 * 		2. 数据加载完成可以调用   uni.stopPullDownRefresh() 停止刷新
 * 		3. 还可以手动调用 uni.startPullDownRefresh() 开启刷新
 */
onPullDownRefresh(() => {
  // 将页码重置为1
  query.pageNum = 1;
  // 将list重置为[]
  state.list = [];
  load(() => {
    uni.stopPullDownRefresh();
  });
});

onMounted(() => {
  // load()
  uni.startPullDownRefresh();
});
</script>
